package com.example.studytest.Controller.Admin;


import com.csvreader.CsvWriter;
import com.example.studytest.Entity.Admin.TestOneRecordView;
import com.example.studytest.Entity.Test1.TestOneRecord;
import com.example.studytest.Entity.Test2.Aural_sd;
import com.example.studytest.Entity.Test3.TestThreeRecord;
import com.example.studytest.Entity.Test4.Test4_info;
import com.example.studytest.Entity.User.T_user;
import com.example.studytest.Entity.word.laa.Laa;
import com.example.studytest.Entity.word.sd.Word_sd;
import com.example.studytest.Entity.word.vl.Vl;
import com.example.studytest.Entity.word.wm.Wm;
import com.example.studytest.Repository.Admin.TestOneRecordViewRepository;
import com.example.studytest.Repository.Test1.TestOneRepository;
import com.example.studytest.Repository.Test2.Aural_sd_repository;
import com.example.studytest.Repository.Test3.TestThreeRepository;
import com.example.studytest.Repository.Test4.Test4_infoRepository;
import com.example.studytest.Repository.User.T_userRepository;
import com.example.studytest.Repository.word.laa.LaaRepository;
import com.example.studytest.Repository.word.vl.VlRepository;
import com.example.studytest.Repository.word.wm.WmRespository;
import com.example.studytest.Repository.word.word_sd.Word_sdRepository;
import com.example.studytest.Util.CreateSheetUtil;
import com.example.studytest.Util.ObjectToListUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/download")
public class DownloadController {
    @Autowired
    private T_userRepository t_userRepository;

    @Autowired
    private TestOneRepository testOneRepository;
    @Autowired
    private VlRepository vlRepository;

    @Autowired
    private Aural_sd_repository auralSdRepository;
    @Autowired
    private Word_sdRepository wordSdRepository;

    @Autowired
    private Test4_infoRepository test4InfoRepository;
    @Autowired
    private WmRespository wmRespository;

    @Autowired
    private TestThreeRepository testThreeRepository;
    @Autowired
    private LaaRepository laaRepository;

    @Autowired
    private T_userRepository tUserRepository;
    @GetMapping("/downloadData/{testName}/{year}/{month}/{day}")
    public void downloadData(@PathVariable("testName") String testName,
                             @PathVariable("year") String year,
                             @PathVariable("month") String month,
                             @PathVariable("day") String day,
                             HttpServletResponse response) throws IOException {
        String date = year + "/" + month + "/" + day;
        String fileName = "data.csv";
        String[] heads;
        File csv_data = new File(fileName);
        switch (testName) {
            case "aural_vl":
                List<TestOneRecord> testOneRecords = testOneRepository.findByDate(date);
                heads = ObjectToListUtil.getFieldsName(testOneRecords.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, testOneRecords);
                break;
            case "written_vl":
                List<Vl> vls = vlRepository.findByDate(date);
                heads = ObjectToListUtil.getFieldsName(vls.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, vls);
                break;
            case "aural_sd":
                List<Aural_sd> auralSds = auralSdRepository.findByDate(date);
                heads = ObjectToListUtil.getFieldsName(auralSds.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, auralSds);
                break;
            case "written_sd":
                List<Word_sd> wordSds = wordSdRepository.findByDate(date);
                heads = ObjectToListUtil.getFieldsName(wordSds.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, wordSds);
                break;
            case "aural_wm":
                List<Test4_info> test4Infos = test4InfoRepository.findByDate(date);
                heads = ObjectToListUtil.getFieldsName(test4Infos.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, test4Infos);
                break;
            case "written_wm":
                List<Wm> wms = wmRespository.findByDate(date);
                heads = ObjectToListUtil.getFieldsName(wms.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, wms);
                break;
            case "aural_laa":
                List<TestThreeRecord> testThreeRecords = testThreeRepository.findByDate(date);
                heads = ObjectToListUtil.getFieldsName(testThreeRecords.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, testThreeRecords);
                break;
            case "written_laa":
                List<Laa> laas = laaRepository.findByDate(date);
                heads = ObjectToListUtil.getFieldsName(laas.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, laas);
                break;
            default:
                List<T_user> tUsers = tUserRepository.findAll();
                heads = ObjectToListUtil.getFieldsName(tUsers.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, tUsers);
        }


        response.setContentType("application/csv; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        InputStream in = new FileInputStream(csv_data);
        OutputStream out = response.getOutputStream();
        byte[] bs = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};   //new added
        out.write(bs);
        int len;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }

    }

    @GetMapping("/downloadByEmail/{testName}/{Remail}")
    public void downloadDataByRemail(@PathVariable("testName") String testName,
                                     @PathVariable("Remail") String Remail, HttpServletResponse response) throws IOException {
        String fileName = "data.csv";
        String[] heads;
        File csv_data = new File(fileName);
        List<String> emailList = t_userRepository.findEmailByRemail(Remail);
        System.out.println(emailList);

        switch (testName) {
            case "aural_vl":
                List<TestOneRecord> test1Records = new ArrayList<TestOneRecord>();

                for (int i=0;i<emailList.size();i++){
                    System.out.println(i);
                    test1Records.addAll(testOneRepository.findByEmail(emailList.get(i)));
                }
                heads = ObjectToListUtil.getFieldsName(test1Records.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, test1Records);
                break;
            case "written_vl":
                List<Vl> VlRecords = new ArrayList<Vl>();
                for (int i=0;i<emailList.size();i++){
                    VlRecords.addAll(vlRepository.findByEmail(emailList.get(i)));
                }
                heads = ObjectToListUtil.getFieldsName(VlRecords.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, VlRecords);
                break;
            case "aural_sd":
                List<Aural_sd> test2Records = new ArrayList<Aural_sd>();
                for (int i=0;i<emailList.size();i++){
                    test2Records.addAll(auralSdRepository.findByEmail(emailList.get(i)));
                }
                heads = ObjectToListUtil.getFieldsName(test2Records.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, test2Records);
                break;
            case "written_sd":
                List<Word_sd> SdRecords = new ArrayList<Word_sd>();
                for (int i=0;i<emailList.size();i++){
                    SdRecords.addAll(wordSdRepository.findByEmail(emailList.get(i)));
                }
                heads = ObjectToListUtil.getFieldsName(SdRecords.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, SdRecords);
                break;
            case "aural_wm":
                List<Test4_info> test4Records = new ArrayList<Test4_info>();
                for (int i=0;i<emailList.size();i++){
                    test4Records.addAll(test4InfoRepository.findByEmail(emailList.get(i)));
                }
                heads = ObjectToListUtil.getFieldsName(test4Records.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, test4Records);
                break;
            case "written_wm":
                List<Wm> WmRecords = new ArrayList<Wm>();
                for (int i=0;i<emailList.size();i++){
                    WmRecords.addAll(wmRespository.findByEmail(emailList.get(i)));
                }
                heads = ObjectToListUtil.getFieldsName(WmRecords.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, WmRecords);
                break;
            case "aural_laa":
                List<TestThreeRecord> test3Records = new ArrayList<TestThreeRecord>();
                for (int i=0;i<emailList.size();i++){
                    test3Records.addAll(testThreeRepository.findByEmail(emailList.get(i)));
                }
                heads = ObjectToListUtil.getFieldsName(test3Records.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, test3Records);
                break;
            case "written_laa":
                List<Laa> LaRecords = new ArrayList<Laa>();
                for (int i=0;i<emailList.size();i++){
                    LaRecords.addAll(laaRepository.findByEmail(emailList.get(i)));
                }
                heads = ObjectToListUtil.getFieldsName(LaRecords.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, LaRecords);
                break;
            default:
                List<T_user> UserRecords = new ArrayList<T_user>();
                for (int i=0;i<emailList.size();i++){
                    UserRecords.add(tUserRepository.findAllByEmail(emailList.get(i)));
                }
                heads = ObjectToListUtil.getFieldsName(UserRecords.get(0));
                csv_data = CreateSheetUtil.createCsv(fileName, heads, UserRecords);
        }


        response.setContentType("application/csv; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        InputStream in = new FileInputStream(csv_data);
        OutputStream out = response.getOutputStream();
        byte[] bs = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};   //new added
        out.write(bs);
        int len;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }


    }
}
